package com.relatev.minecraft.UWantRestart.Sponge;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.relatev.minecraft.UWantRestart.RestartCondition;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import org.spongepowered.api.Sponge;

public class SPConfigManager {

    private static HoconConfigurationLoader ConfigLoader;
    private static File ConfigFile;
    public static CommentedConfigurationNode RootNode;
    private static Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().disableInnerClassSerialization().create();
    public static List<RestartCondition> Conditions;

    public static void init() {
        ConfigFile = new File(Sponge.getConfigManager().getPluginConfig(UWantRestartSP.MainPlugin).getDirectory().toFile(), "config.yml");
        if (ConfigFile.exists() == false) {
            ConfigFile.getParentFile().mkdirs();
            try {
                ConfigFile.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(SPConfigManager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        ConfigLoader = HoconConfigurationLoader.builder().setFile(ConfigFile).build();
        try {
            RootNode = ConfigLoader.load();
            if (RootNode.getNode("Version").getInt() != 100) {
                RootNode.getNode("Version").setValue(100);
                RootNode.getNode("RestartConditions").setValue(Arrays.asList(gson.toJson(new RestartCondition(23, 5, 5))));
                RootNode.getNode("KickMessage").setValue("§c服务器将重新启动\n§b请等待一下重新登录游戏");
            }
            ConfigLoader.save(RootNode);
        } catch (IOException ex) {
            Logger.getLogger(SPConfigManager.class.getName()).log(Level.SEVERE, null, ex);
        }
        Conditions = new ArrayList();
        try {
            for (String jsonstring : RootNode.getNode("RestartConditions").getList(new TypeToken<String>() {
            })) {
                Conditions.add(gson.fromJson(jsonstring, RestartCondition.class));
            }
        } catch (ObjectMappingException ex) {
            Logger.getLogger(SPConfigManager.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
